#include "analogclock.h"


AnalogClock::AnalogClock(QWidget *parent)
    : QWidget(parent)
{
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &AnalogClock::update);
    timer->start(1000);
    resize(200, 200);
}

AnalogClock::~AnalogClock()
{
}

void AnalogClock::update()
{
    QWidget::update();
}

void AnalogClock::paintEvent(QPaintEvent *)
{
    static const QPoint hourHand[3] = {
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -40)
    };
    static const QPoint minuteHand[3] = {
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -70)
    };
    QColor hourColor(127, 0, 127);
    QColor minuteColor(0, 127, 127, 191);
    int side = qMin(width(), height());
    QTime time = QTime::currentTime();
    QPainter painter(this);

    painter.setRenderHint(QPainter::Antialiasing);
    //将原点平移（ translate）到 widget 的中间
    painter.translate(width() / 2, height() / 2);
    painter.scale(side / 200.0, side / 200.0);
    //设置钢笔和笔刷
    painter.setPen(Qt::NoPen);
    painter.setBrush(hourColor);

    //绘制时针， 利用 Qt 支持渲染时旋转的特性，将视口旋转适当的角度以放置时针（每个小时旋转 30 度）
    painter.save();
    painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
    painter.drawConvexPolygon(hourHand, 3);
    painter.restore();

    //绘制时刻度
    painter.setPen(hourColor);
    for (int i = 0; i < 12; ++i) {
        painter.drawLine(88, 0, 96, 0);
        painter.rotate(30.0);
    }

    //绘制分针
    painter.setPen(Qt::NoPen);
    painter.setBrush(minuteColor);
    painter.save();
    painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
    painter.drawConvexPolygon(minuteHand, 3);
    painter.restore();
    //绘制60个分刻度
    painter.setPen(minuteColor);
    for (int j = 0; j < 60; ++j) {
        if ((j % 5) != 0)
            painter.drawLine(92, 0, 96, 0);
        painter.rotate(6.0);
    }
}


